Shader "Hidden/Fullscreen/ThresholdExtractSeparated"
{
    HLSLINCLUDE
    #pragma vertex Vert

    #pragma target 4.5
    #pragma only_renderers d3d11 ps4 xboxone vulkan metal switch

    #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/CustomPass/CustomPassCommon.hlsl"

    TEXTURE2D_X(_CharacterMaskTex);
    TEXTURE2D_X(_Source);
    float _Threshold;
    float _Intensity;
    float _SceneViewMode;
    float _IsCharacterBloom; // 1.0表示角色Bloom，0.0表示场景Bloom


    float4 ThresholdExtract(Varyings varyings) : SV_Target
    {
        UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(varyings);

        // 为Scene视图优化UV计算
        float2 uv = varyings.positionCS.xy * _ScreenSize.zw;
        if (_SceneViewMode < 0.5) // Game视图
        {
            uv = uv * 2;
        }
        else // Scene视图
        {
            uv = uv * _RTHandleScale.xy * 2;
        }

        float4 color = SAMPLE_TEXTURE2D_X_LOD(_Source, s_linear_clamp_sampler, uv, 0);
        float4 characterMask = SAMPLE_TEXTURE2D_X_LOD(_CharacterMaskTex, s_linear_clamp_sampler, uv, 0);


        if (_IsCharacterBloom ==1.0f)
        {
            // 角色Bloom：只处理角色区域（白色区域）
            color.rgb = max(color.rgb - _Threshold, 0.0) * characterMask.r;
        }
        else
        {
            // 场景Bloom：只处理场景区域（黑色区域）
            color.rgb = max(color.rgb - _Threshold, 0.0) * (1.0 - characterMask.r);
        }
        // 阈值提取：color - threshold，如果结果为负则设为0
        // color.rgb = max(color.rgb - _Threshold, 0.0)*characterMask;
          // color.rgb = max(color.rgb - _Threshold, 0.0) * (1.0 - characterMask.r);

        // 应用强度
        color.rgb *= 1;

        return color;
    }
    ENDHLSL

    SubShader
    {
        Pass
        {
            Name "Threshold Extract"
            Stencil
            {
                Ref 4 // 参考值
                Comp Equal

            }

            ZWrite Off
            ZTest Always

            Cull Off

            HLSLPROGRAM
            #pragma fragment ThresholdExtract
            ENDHLSL

        }
    }
    Fallback Off
}